﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Net.Sockets;
using System.Threading;
using System.Net;

namespace DA_CLIENT
{
    public partial class FrmChatVoiceServer : DevExpress.XtraEditors.XtraForm
    {
        private Socket ClientSocket;
        private DirectSoundHelper sound;
        private byte[] buffer = new byte[2205];
        private Thread th;
        public FrmChatVoiceServer()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            
        }

        private void ConnectServer(string ServerIP, int Port)
        {
            try
            {
                if (ClientSocket != null && ClientSocket.Connected)
                {
                    ClientSocket.Shutdown(SocketShutdown.Both);
                    System.Threading.Thread.Sleep(10);
                    ClientSocket.Close();
                }

                ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint Server_EndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), Port);
                ClientSocket.Blocking = false;

                ClientSocket.BeginConnect(Server_EndPoint, new AsyncCallback(OnConnectServer), ClientSocket);

                th = new Thread(new ThreadStart(sound.StartCapturing));
                th.IsBackground = true;
                th.Start();
            }
            catch (Exception) { }
        }

        private void OnConnectServer(IAsyncResult ar)
        {
            Socket sock = (Socket)ar.AsyncState;

            try
            {
                if (sock.Connected)
                {
                    SetupRecieveCallbackServer(sock);
                    //btnJoinServer.Enabled = false;
                    btnTalkServer.Enabled = true;
                }
                else
                {
                    DisconncetServer();
                    //btnJoinServer.Enabled = true;
                    btnTalkServer.Enabled = false;
                    MessageBox.Show("Connection Failed");
                }
            }
            catch (Exception) { }
        }
        public void SetupRecieveCallbackServer(Socket sock)
        {
            try
            {
                AsyncCallback recieveData = new AsyncCallback(OnRecievedDataServer);
                sock.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, recieveData, sock);
            }
            catch (Exception) { }
        }

        private void OnRecievedDataServer(IAsyncResult ar)
        {
            Socket sock = (Socket)ar.AsyncState;

            try
            {
                int nBytesRec = sock.EndReceive(ar);
                if (nBytesRec > 0)
                {
                    sound.PlayReceivedVoice(buffer);

                    SetupRecieveCallbackServer(sock);
                }
                else
                {
                    sock.Shutdown(SocketShutdown.Both);
                    sock.Close();
                }
            }
            catch (Exception) { }
        }
        void DisconncetServer()
        {
            try
            {
                if (ClientSocket != null & ClientSocket.Connected)
                {
                    ClientSocket.Close();
                }
            }
            catch (Exception) { }
        }

        private void btnTalkServer_Click(object sender, EventArgs e)
        {
            IPHostEntry IP = Dns.GetHostByName(Dns.GetHostName().ToString());
            string tempIP = IP.AddressList[0].ToString(); // IP máy phản hồi
            //Truyền IP Client và cổng CLient
            ConnectServer(tempIP    , 5000);
            sound.StopLoop = false;

            btnTalkServer.Enabled = false;
            btnStopServer.Enabled = true;
        }

        private void btnStopServer_Click(object sender, EventArgs e)
        {
            sound.StopLoop = true;

            btnTalkServer.Enabled = true;
            btnStopServer.Enabled = false;
        }

        private void FormClosingDong(object sender, FormClosingEventArgs e)
        {
            DisconncetServer();
        }

        private void FrmChatVoiceServer_Load(object sender, EventArgs e)
        {
            sound = new DirectSoundHelper();
            sound.OnBufferFulfill += new EventHandler(SendVoiceBufferServer);
        }

        private void SendVoiceBufferServer(object VoiceBuffer, EventArgs e)
        {
            byte[] Buffer = (byte[])VoiceBuffer;

            SendBufferServer(Buffer);
        }

        private void SendBufferServer(byte[] Buffer)
        {
            ClientSocket.Send(buffer, SocketFlags.None);
        }
    }
}